package com.chaoxi.picturebackend.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chaoxi.picturebackend.annotation.AuthCheck;
import com.chaoxi.picturebackend.common.BaseResponse;
import com.chaoxi.picturebackend.common.DeleteRequest;
import com.chaoxi.picturebackend.common.ResultUtils;
import com.chaoxi.picturebackend.constant.UserConstant;
import com.chaoxi.picturebackend.exception.BusinessException;
import com.chaoxi.picturebackend.exception.ErrorCode;
import com.chaoxi.picturebackend.exception.ThrowUtils;
import com.chaoxi.picturebackend.model.dto.user.*;
import com.chaoxi.picturebackend.model.entity.User;
import com.chaoxi.picturebackend.model.vo.LoginUserVO;
import com.chaoxi.picturebackend.model.vo.UserVO;
import com.chaoxi.picturebackend.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/user")
@Api("用户接口")
public class UserController {
    @Resource
    private UserService userService;
    
    /**
     * 用户注册
     * @param request 注册请求
     * @return 新用户id
     */
    @PostMapping("/register")
    @ApiOperation("用户注册")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR, "参数为空");
        String userAccount = request.getUserAccount();
        String userPassword = request.getUserPassword();
        String checkPassword = request.getCheckPassword();
        long result = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(result);
    }

    /**
     *  用户登录
     * @param loginRequest 登录请求
     * @param request 登录请求
     * @return 脱敏后的用户信息
     */
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest loginRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR, "参数为空");
        String userAccount = loginRequest.getUserAccount();
        String userPassword = loginRequest.getUserPassword();
        LoginUserVO loginUserVO = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(loginUserVO);
    }

    /**
     * 修改密码
     *
     * @param changePasswordRequest 修改密码请求
     * @param request               HttpServletRequest
     * @return 是否修改成功
     */
    @PostMapping("/changePassword")
    @ApiOperation("用户修改密码")
    public BaseResponse<Boolean> changePassword(@RequestBody UserChangePasswordRequest changePasswordRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(changePasswordRequest == null, ErrorCode.PARAMS_ERROR, "参数为空");
        String oldPassword = changePasswordRequest.getOldPassword();
        String newPassword = changePasswordRequest.getNewPassword();
        String confirmNewPassword = changePasswordRequest.getConfirmNewPassword();
        
        // 校验新密码与确认密码一致
        ThrowUtils.throwIf(!newPassword.equals(confirmNewPassword), ErrorCode.PARAMS_ERROR, "两次输入的新密码不一致");
        
        boolean result = userService.changePassword(oldPassword, newPassword, request);
        return ResultUtils.success(result);
    }
    
    /**
     * 获取当前登录用户
     * @param request 请求
     * @return 当前登录用户
     */
    @GetMapping("get/login")
    @ApiOperation("获取当前登录用户")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        return ResultUtils.success(userService.objToVo(loginUser));
    }

    /**
     * 用户登出
     * @param request 登出请求
     * @return 登出结果
     */
    @PostMapping("/logout")
    @ApiOperation("用户登出")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR, "请求为空");
        return ResultUtils.success(userService.userLogout(request));
    }

    /**
     * 添加用户
     * @param userAddRequest 添加用户请求
     * @return 添加用户结果
     */
    @PostMapping("/add")
    @ApiOperation("添加用户")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest){
        ThrowUtils.throwIf(userAddRequest == null, ErrorCode.PARAMS_ERROR, "参数为空");
        User user = new User();
        BeanUtil.copyProperties(userAddRequest, user);
        // 设置默认密码
        final String DEFAULT_PASSWORD = "12345678";
        final String pre_name = "潮汐图库用户_";
        String encryptedPassword = userService.getEncryptedPassword(DEFAULT_PASSWORD);
        user.setUserPassword(encryptedPassword);
        user.setUserName(pre_name + userAddRequest.getUserName());
        //插入数据库
        boolean save = userService.save(user);
        ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR, "添加用户失败");
        return ResultUtils.success(user.getId());
    }

    /**
     * 根据 id 获取用户（仅管理员）
     * @param id 用户ID
     * @return 用户信息
     */
    @GetMapping("/get")
    @ApiOperation("根据 id 获取用户（仅管理员）")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUserById(long id) {
        // 参数校验
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR, "参数为空");

        // 查询用户信息
        User user = userService.getById(id);

        // 检查用户是否存在
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR, "用户不存在");

        // 返回成功结果
        return ResultUtils.success(user);
    }


    /**
     * 根据 id 获取包装类
     * @param id 用户ID
     * @return 用户包装类信息
     */
    @GetMapping("/get/vo")
    @ApiOperation("根据 id 获取包装类")
    public BaseResponse<UserVO> getUserVOById(long id) {
        // 获取用户基础信息
        BaseResponse<User> response = getUserById(id);
        User user = response.getData();
        // 转换为用户包装类并返回
        return ResultUtils.success(userService.getUserVO(user));
    }

    /**
     * 删除用户
     * @param deleteRequest 删除请求参数，包含要删除的用户ID
     * @return 删除结果，成功返回true，失败返回false
     */
    @PostMapping("/delete")
    @ApiOperation("删除用户")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
        ThrowUtils.throwIf(deleteRequest == null, ErrorCode.PARAMS_ERROR, "参数为空");
        Long id = deleteRequest.getId();
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        // 执行删除操作
        boolean result = userService.removeById(deleteRequest.getId());
        userService.clearUserCache(user);
        return ResultUtils.success(result);
    }

    /**
     * 用户编辑个人信息
     * @param userEditRequest 用户编辑请求参数，包含要更新的用户信息
     * @param request HTTP请求对象，用于获取当前登录用户
     * @return 编辑结果，成功返回true，失败抛出异常
     */
    @PostMapping("/edit")
    @ApiOperation("用户编辑个人信息")
    public BaseResponse<Boolean> editUser(@RequestBody UserEditRequest userEditRequest, HttpServletRequest request) {
        // 参数校验
        ThrowUtils.throwIf(userEditRequest == null, ErrorCode.PARAMS_ERROR, "参数为空");

        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);

        // 构造更新对象
        User user = new User();
        BeanUtils.copyProperties(userEditRequest, user);
        // 确保只能更新自己的信息
        user.setId(loginUser.getId());

        // 执行更新操作
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "更新用户信息失败");
        userService.clearUserCache(user);
        return ResultUtils.success(true);
    }


    /**
     * 更新用户信息
     *
     * @param userUpdateRequest 用户更新请求参数，包含要更新的用户信息
     * @return 更新结果，成功返回true，失败抛出异常
     */
    @PostMapping("/update")
    @ApiOperation("更新用户信息")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest) {
        // 参数校验
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        // 复制属性并执行更新操作
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "更新用户失败");
        userService.clearUserCache(user);
        return ResultUtils.success(true);
    }


    /**
     * 分页获取用户VO列表
     *
     * @param userQueryRequest 用户查询请求参数，包含分页信息和查询条件
     * @return BaseResponse<Page<UserVO>> 包含分页用户VO数据的统一响应结果
     */
    @PostMapping("/list/page/vo")
    @ApiOperation("分页获取用户VO列表")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest) {
        // 参数校验
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR, "请求参数为空");

        // 获取分页参数
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();

        // 执行分页查询
        Page<User> userPage = userService.page(new Page<>(current, size), userService.getQueryWrapper(userQueryRequest));

        // 转换为VO对象并封装分页结果
        Page<UserVO> userVOPage = new Page<>(current, size, userPage.getTotal());
        List<UserVO> userVOList = userService.getUserVOList(userPage.getRecords());
        userVOPage.setRecords(userVOList);

        return ResultUtils.success(userVOPage);
    }




}
